<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

/**
 * 스타 운세 데이터 생성 컨트롤러
 * 연예인의 사주정보를 토대로 운세 결과 키값(db_express)을 생성해 DB에 저장한다.
 */
class Starpt extends CI_Controller {
	
	var $data = array();
	
	function __construct() {
		parent::__construct();
		$this->data['sess_userinfo'] = $this->session->userdata('userinfo');

		$this->load->model('star/Starpt_model', 'starpt');
		$this->load->helper(array('pagenavi'));
	}
	
	// Default
	function index() {
		$this->starpt_list();
	}
	
	/**
	 * 스타 정보 리스트
	 */
	function starpt_list() {
		log_message('debug', "@@@@ Starpt::starpt_list()");
		
		$search_type    = $this->input->get('search_type', TRUE);
		$search_keyword = $this->input->get('search_keyword', TRUE);
		$page           = $this->input->get('page', TRUE);

		$search_type    = empty($search_type) ? '' : $search_type;
		$search_keyword = empty($search_keyword) ? '' : $search_keyword;
		$current_page   = empty($page) ? 1 : $page;

		$page_size  = LIST_PAGE_SIZE;		// 한 페이지에 보여줄 글 수
		$block_size = LIST_BLOCK_SIZE;	// 네비영역의 한 블록에 보여줄 페이지 수

		$total_cnt  = $this->starpt->get_starpt_total_count($search_type, $search_keyword);	// 총 글 수

		$this->data['list'] = $this->starpt->select_starpt_list($search_type, $search_keyword, $current_page, $page_size);

		$this->data['navi'] = page_navigation($current_page, $total_cnt, $page_size, $block_size);
		
		$this->load->view('star/starpt_list_v', $this->data);
	}	

	/**
	 * 글쓰기 폼
	 */
	function write() {
		log_message('debug', "@@@@ Starpt::write()");
		
		$this->load->view('star/starpt_write_v', $this->data);
	}
	
	/**
	 * 글쓰기 완료
	 */
	function write_ok() {
		log_message('debug', "@@@@ Starpt::_write_ok()");

		$cate = 'starpt';
		
		
		echo "<pre>";
		print_r($_FILES);
		echo "</pre>";

		
		// 파일 저장
		$result_upload = $this->_do_upload($cate);
		
		// 썸네일 생성
		if (!empty($result_upload)) {
			$this->load->library('image_lib'); 
			$this->_create_thumb($result_upload[0], STARPT_THUMB_WIDTH, STARPT_THUMB_HEIGHT);	// 메인용
			$this->_create_thumb($result_upload[0], 67, 51);	// 서브용
		}
		
		// 글 저장 (파일이 성공적으로 저장됐을때만 글 저장)
		$bbs_content['category']   = $cate;
		$bbs_content['user_id']    = $this->data['sess_userinfo']['user_id'];
		$bbs_content['nickname']   = $this->data['sess_userinfo']['nickname'];
		$bbs_content['subject']    = $this->input->post('subject', TRUE);
		$bbs_content['content']    = $this->input->post('content', TRUE);
		$bbs_content['artist_idx'] = $this->input->post('artist_idx', TRUE);
		
		$this->starpt->save_starpt($bbs_content, $result_upload);

		redirect("/star/starpt");
	}
	
	/**
	 * 파일 업로드
	 */
	function _do_upload($cate) {
		log_message('debug', "@@@@ Starpt::_do_upload($cate)");

		$target_dir = FILE_UPLOAD_DIR_UNSIN.$cate."/".date('Ym',time());
		$target_url = FILE_UPLOAD_URL_UNSIN.$cate."/".date('Ym',time());

		if(!is_dir($target_dir)){
		   mkdir($target_dir, DIR_WRITE_MODE);
		}
		
		$result_upload = array();
		for ($i=0; $i < count($_FILES["userfile"]["name"]); $i++) {
			if ($_FILES["userfile"]["error"][$i] == 4) {
				continue;
			} 
			
			if ($_FILES["userfile"]["error"][$i] > 0) {
				echo "Error: " . $_FILES["userfile"]["error"][$i] . "<br />";
			} else {
				$orig_name = $_FILES["userfile"]["name"][$i];
				$ext_pos = strlen($orig_name)-strpos(strrev($orig_name),'.')-1;
				$file_ext = substr($orig_name, $ext_pos, strlen($orig_name));
				
				mt_srand();
				$filename = md5(uniqid(mt_rand())).$file_ext;

				$ext_pos = strlen($filename)-strpos(strrev($filename),'.')-1;
				$raw_name = substr($filename, 0, $ext_pos);

				$result_upload[$i]["file_name"] = $filename;
				$result_upload[$i]["orig_name"] = $_FILES["userfile"]["name"][$i];
				$result_upload[$i]["raw_name"]  = $raw_name;
				$result_upload[$i]["file_ext"]  = $file_ext;
				$result_upload[$i]["file_path"] = $target_dir.'/';
				$result_upload[$i]["file_url"]  = $target_url.'/';
				$result_upload[$i]["file_type"] = $_FILES["userfile"]["type"][$i];
				$result_upload[$i]["file_size"] = $_FILES["userfile"]["size"][$i]/1024;
				$result_upload[$i]["is_image"] = 'Y';
								
				move_uploaded_file($_FILES["userfile"]["tmp_name"][$i], $target_dir.'/'.$filename);
			}

			echo "<br/><br/>";
		}

		return $result_upload;
	}

	/**
	 * 섬네일 이미지 만들기
	 */
	function _create_thumb($result_upload, $width, $height) {
		log_message('debug', "@@@@ Starpt::_create_thumb($result_upload, $width, $height)");

		echo "<pre>";
		print_r($result_upload);
		echo "</pre>";
				
		$config['image_library']  = 'gd2';
		$config['source_image']   = $result_upload['file_path'].$result_upload['file_name'];
		$config['new_image']      = $result_upload['file_path'].$result_upload['raw_name']."_$width".$result_upload['file_ext'];
		$config['create_thumb']   = TRUE;
		$config['thumb_marker']   = FALSE;
		$config['maintain_ratio'] = TRUE;	// 가로세로 비율 유지
		$config['master_dim']     = 'auto';	// 크기 조절시 큰 축을 기준
		$config['width']	      = $width;
		$config['height']         = $height;

		$this->image_lib->clear();
		$this->image_lib->initialize($config);
		$this->image_lib->resize();
	}
	
	/*******************************************************************
	 * 삭제
	 *******************************************************************/
	function remove_ok() {
		$idx  = $this->input->post('idx');
		$page = $this->input->post('page');
		$this->starpt->remove_bbs($idx);
		echo "<script type='text/javascript'>alert('삭제완료');location.href='/star/starpt?page=".$page."';</script>";
	}
	
	/*******************************************************************
	 * 스타 검색 폼
	 *******************************************************************/
	function search() {
		log_message('debug', "@@@@ Star::search()");

		$search_keyword = $this->input->post('search_keyword', TRUE);
		if (!empty($search_keyword)) {
			$this->data['search_keyword'] = $search_keyword;
			$this->data['artist_list'] = $this->starpt->select_artist_search_list($search_keyword);
		} else {
			$this->data['search_keyword'] = '';
		}
		
		$this->load->view('star/star_search_pop_v', $this->data);
	}

}


/* End of file starpt.php */
/* Location: ./application/controllers/star/starpt.php */